import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnInit,
  TemplateRef,
  ViewChild
} from '@angular/core';
import {MsdsEnterpriseList, SearchCommonVO} from "../../core/services/types";
import {FormBuilder, FormGroup} from "@angular/forms";
import {MyTableConfig} from "../../shared/components/ant-table/ant-table.component";
import {PageHeaderType} from "../../shared/components/page-header/page-header.component";
import {ActivatedRoute, Router} from "@angular/router";
import {MsdsHttpService} from 'src/app/core/services/http/msds/msds-enterprise.service';
import {NzTableQueryParams} from "ng-zorro-antd/table";
import {finalize} from "rxjs/operators";
import {NzModalService} from "ng-zorro-antd/modal";
import FileSaver from "file-saver";
import {MsdsIdService} from "../../core/services/store/biz-store-service/msds-id/msds-id.service";
import {AdminService} from "../../core/services/store/admin.service";
import {WindowService} from "../../core/services/common/window.service";
import {AdminKey} from "../../config/constant";
import {NzMessageService} from "ng-zorro-antd/message";


interface SearchParam {
  dangerNo: string;
  cnName: string;
  cas: string;
}

@Component({
  selector: 'app-msds',
  templateUrl: './msds.component.html',
  styleUrls: ['./msds.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MsdsComponent implements OnInit {
  searchParam: Partial<SearchParam> = {};
  @ViewChild('operationTpl', {static: true}) operationTpl!: TemplateRef<any>;
  validateForm!: FormGroup;
  tableConfig!: MyTableConfig;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '列表展示',
    breadcrumb: ['首页', 'SDS', '名称展示']
  };
  dataList: MsdsEnterpriseList[] = [];

  constructor(private fb: FormBuilder, private router: Router,
              private msdsIdService: MsdsIdService, private message: NzMessageService,
              private cdr: ChangeDetectorRef, private dataService: MsdsHttpService,
              private modalSrv: NzModalService, private windowSrv: WindowService,
              public AdminService: AdminService, private activatedRoute: ActivatedRoute) {
  }

  reloadTable(): void {
    this.message.info('刷新成功');
    this.tableConfig.pageIndex = 1;
    this.getDataList();
  }

  search(): void {
    this.tableConfig.pageIndex = 1;
    this.getDataList();
  }

  // 触发表格变更检测
  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableLoading(true);
    const params: SearchCommonVO<any> = {
      pageSize: this.tableConfig.pageSize!,
      pageNum: e?.pageIndex || this.tableConfig.pageIndex!,
      filters: this.searchParam
    };
    this.dataService.getMsdsList(params).pipe(finalize(() => this.tableLoading(false))).subscribe((data) => {
      const {list, total, pageNum} = data;
      this.dataList = [...list];
      this.tableConfig.total = total!;
      this.tableConfig.pageIndex = pageNum!;
      this.tableLoading(false);
    });
  }


  /*重置*/
  resetForm(): void {
    this.searchParam = {};
    this.tableConfig.pageIndex = 1;
    this.getDataList();
  }

  /*新增*/
  add(): void {
    this.msdsIdService.setMsdsIdStore(-1);
    this.router.navigate(['default/msds/add-edit-list']);
  }

  // 修改
  edit(id: number): void {
    this.msdsIdService.setMsdsIdStore(id);
    this.router.navigate(['/default/msds/add-edit-list']);
  }

  /*删除*/
  del(id: number[]): void {
    this.modalSrv.confirm({
      nzTitle: '确定要删除吗？',
      nzContent: '删除后不可恢复',
      nzOnOk: () => {
        this.tableLoading(true);
        this.dataService.delMsdsList(id).pipe(finalize(() => {
          this.tableLoading(false);
        })).subscribe(() => {
          if (this.dataList.length === 1) {
            this.tableConfig.pageIndex--;
          }
          this.getDataList();
          // @ts-ignore
          this.checkedCashArray.splice(this.checkedCashArray.findIndex(item => item.id === id), 1);
        }, error => this.tableLoading(false));
      }
    });
  }

  /*document*/
  msdsExport(id: number, cnName: string): void {
    this.dataService.getMsdsExport(id).subscribe(res => {
      const blob = new Blob([res], {type: 'text/plain;charset=utf-8'});
      FileSaver.saveAs(blob, `${cnName}安全技术说明书（SDS）.doc`);
    })
  }

  /*safe-label*/

  /* safetyExport(id: number, name: string): void {
     this.dataService.getSafetyExport(id).subscribe(res => {
       const blob = new Blob([res], {type: 'text/plain;charset=utf-8'});
       FileSaver.saveAs(blob, `${name}安全标签.doc`);
     })
   }*/

  _onReuseInit(): void {
    this.getDataList();
  }

  // 修改一页几条
  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }


  ngOnInit(): void {
    this.initTable();
    this.activatedRoute.queryParams.subscribe(res => {
      if (typeof (res['userId']) != undefined) {
        if (res['userId'] === '1') {
          this.AdminService.isAdmin = true;
          this.windowSrv.setSessionStorage(AdminKey, res['userId']);
        }
      }
    });
  }

  private initTable(): void {
    this.tableConfig = {
      needNoScroll: true,
      showCheckbox: false,
      headers: [
        {
          title: '危化品序号',
          width: 200,
          field: 'dangerNo',
        },
        {
          title: '中文名',
          width: 350,
          field: 'cnName',
        },
        {
          title: '英文名',
          width: 500,
          field: 'enName',
        },
        {
          title: 'CAS号',
          width: 200,
          field: 'cas',
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          fixed: true,
          fixedDir: "right"
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1,
    };
  }

}
